package cn.mldn.homework.reflection;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


/**
 * 反射提取Person类属性值步骤如下
 * 1.创建Person实例，并为每个属性赋值
 * 2.获取所有属性，及属性值
 * 3.写入文本文件
 */
public class StoreAttrToTxt
{
	private Person person = new Person();
	private StringBuilder sb = new StringBuilder();

	public static void main(String[] args)
	{
		StoreAttrToTxt totxt = new StoreAttrToTxt();
		totxt.setAttr();
		totxt.getAttr();
		totxt.outputToTxt();
		
		System.out.println("保存属性值到文件成功！");
	}
	
	private void setAttr()
	{
		person.setIdNo("4408821998");
		person.setName("郭杰瑞");
		person.setAge(21);
		person.setSex("Male");
		person.setIsMerried(false);
	}

	private void getAttr()
	{
		Class clazz = person.getClass();
		Field[] field = clazz.getDeclaredFields();
		
		for (Field f : field)
		{
			String fieldName = f.getName();
			String methodName = "get" + StringUtil.firstCharToUpper(fieldName);
			
			sb.append(fieldName + " = ");
			
			try
			{
				Method method = clazz.getMethod(methodName);
				Object value = method.invoke(person);
				
				sb.append(value + "\n");
			} catch (SecurityException e)
			{
				e.printStackTrace();
			} catch (NoSuchMethodException e)
			{
				e.printStackTrace();
			} catch (IllegalArgumentException e)
			{
				e.printStackTrace();
			} catch (IllegalAccessException e)
			{
				e.printStackTrace();
			} catch (InvocationTargetException e)
			{
				e.printStackTrace();
			}
		}
	}

	private void outputToTxt()
	{
		Class clazz = person.getClass();
		String path = this.getClass().getPackage().getName().replace(".", "\\");
		String url = System.getProperty("user.dir") + "\\src\\" + path + "\\" + clazz.getSimpleName() + ".txt";
		
		try
		{
			FileOutputStream fileOutput = new FileOutputStream(url);
			fileOutput.write(sb.toString().getBytes("UTF-8"));
			
			fileOutput.flush();
			fileOutput.close();
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}
